import LRU from 'lru-cache'

let noParamsOptions = {
    max: 100,
    maxAge: 300 * 1000,//单位是毫秒
}
let withParamsOptions = {
    max: 100,
    maxAge: 300 * 1000,//单位是毫秒
}

let axiosLRU = {
    'noParams':new LRU(noParamsOptions),
    'withParams' : new LRU(withParamsOptions),
}

let storeAxios = {
    setItem(url,value, params) {
        if (!url || !value) return ''

        let cacheKeyType = 'withParams'

        params = params || {}

        params = typeof params === 'object'?JSON.stringify(params):"{}"
        
        if (!params || params === '{}') {
            cacheKeyType =  'noParams'
        }

        let cacheKey = url + '_' + params
        let cacheValue = typeof(value) === 'string'?value:JSON.stringify(value)
        
        axiosLRU[cacheKeyType].set(cacheKey,cacheValue)
    },
    getItem(url,params){
        if (!url) return null

        let cacheKeyType = 'withParams'

        params = params || {}

        params = typeof params === 'object'?JSON.stringify(params):"{}"

        if (!params || params === '{}') {
            cacheKeyType =  'noParams'
        }

        let cacheKey = url + '_' + params
        let cacheValue = axiosLRU[cacheKeyType].get(cacheKey)
        if (!cacheValue) return null

        try {
            let valueObject = JSON.parse(cacheValue)
            return typeof(valueObject) === 'object'?valueObject:null
        }catch(e) {
            return null
        }
    }
}

export default storeAxios